﻿using MediatR;
using Microsoft.Extensions.Logging;
using Sgr.Application.Commands;
using Sgr.Application.Queries;
using Sgr.Exceptions;
using Sgr.UPMS.Domain.Organizations;
using Sgr.UPMS.Domain.Users;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Sgr.UPMS.Application.Commands.Organizations
{
    /// <summary>
    /// 删除组织邀请命令处理程序
    /// </summary>
    public class DeleteOrgInvitationCommandHandler
        : IRequestHandler<DeleteOrgInvitationCommand, CommandResult<bool>>
    {
        private readonly IOrganizationInvitationRepository _invitationRepository;
        private readonly ICurrentUser _currentUser;

        public DeleteOrgInvitationCommandHandler(
            IOrganizationInvitationRepository invitationRepository, ICurrentUser currentUser)
        {
            _invitationRepository = invitationRepository;
            _currentUser = currentUser;
        }

        public async Task<CommandResult<bool>> Handle(
            DeleteOrgInvitationCommand request,
            CancellationToken cancellationToken)
        {
            // 验证参数
            long orgId = QueryHelper.GetOrgId(_currentUser);

            // 获取邀请信息
            var invitation = await _invitationRepository.GetAsync(
                request.InvitationId,
                cancellationToken);

            if (invitation == null)
                return CommandResult.NotFound<bool>($"邀请链接[{request.InvitationId}]不存在");

            if (invitation.OrganizationId != orgId)
                return CommandResult.Invalid<bool>($"邀请链接[{request.InvitationId}]不属于当前组织");

            // 删除邀请链接
            await _invitationRepository.DeleteAsync(invitation, cancellationToken);

            return CommandResult.Success(true);
        }
    }
}